#!/usr/bin/env python3
"""
磁盘监控系统前端构建脚本
实现前端类型检查、编译和复制到后端目录
"""

import os
import shutil
import sys
from pathlib import Path

# 项目根目录
PROJECT_ROOT = Path(__file__).parent.absolute()
FRONTEND_DIR = PROJECT_ROOT / "disk-monitoring-frontend"
BACKEND_DIR = PROJECT_ROOT / "backend"
BACKEND_WEB_DIR = BACKEND_DIR / "web"
BACKEND_DIST_DIR = BACKEND_WEB_DIR / "dist"

def run_command(cmd, cwd=None, check=True):
    """运行命令并返回结果"""
    print(f"运行命令: {cmd}")
    if cwd:
        print(f"工作目录: {cwd}")
    
    # 保存当前目录
    original_dir = os.getcwd()
    try:
        if cwd:
            os.chdir(cwd)
        
        exit_code = os.system(cmd)
        
        if check and exit_code != 0:
            print(f"命令执行失败，返回码: {exit_code}")
            sys.exit(1)
            
        return exit_code
    finally:
        # 恢复原始目录
        os.chdir(original_dir)

def check_frontend_types():
    """执行前端类型检查"""
    print("=" * 50)
    print("步骤1: 执行前端类型检查...")
    print("=" * 50)
    
    # 检查是否存在package.json
    package_json = FRONTEND_DIR / "package.json"
    if not package_json.exists():
        print("错误: 找不到package.json文件")
        sys.exit(1)
    
    # 运行类型检查
    exit_code = run_command("pnpm type-check", cwd=FRONTEND_DIR, check=False)
    if exit_code != 0:
        print("❌ 类型检查失败")
        sys.exit(1)
    else:
        print("✅ 类型检查通过")

def build_frontend():
    """构建前端项目"""
    print("\n" + "=" * 50)
    print("步骤2: 构建前端项目...")
    print("=" * 50)
    
    # 安装依赖
    print("安装前端依赖...")
    run_command("pnpm install", cwd=FRONTEND_DIR)
    
    # 构建项目
    print("构建前端项目...")
    run_command("pnpm run build", cwd=FRONTEND_DIR)
    
    # 检查构建结果
    frontend_dist = FRONTEND_DIR / "dist"
    if not frontend_dist.exists():
        print("错误: 前端构建失败，未生成dist目录")
        sys.exit(1)
    
    print("✅ 前端构建完成")
    return frontend_dist

def copy_frontend_to_backend(frontend_dist):
    """将前端构建结果复制到后端目录"""
    print("\n" + "=" * 50)
    print("步骤3: 复制前端文件到后端...")
    print("=" * 50)
    
    # 确保目标目录存在
    BACKEND_DIST_DIR.mkdir(parents=True, exist_ok=True)
    
    # 清空目标目录
    if BACKEND_DIST_DIR.exists():
        shutil.rmtree(BACKEND_DIST_DIR)
    BACKEND_DIST_DIR.mkdir(parents=True, exist_ok=True)
    
    # 复制文件
    print(f"从 {frontend_dist} 复制到 {BACKEND_DIST_DIR}")
    
    # 复制dist目录下的所有文件
    for item in frontend_dist.iterdir():
        if item.is_file():
            shutil.copy2(item, BACKEND_DIST_DIR / item.name)
        elif item.is_dir():
            shutil.copytree(item, BACKEND_DIST_DIR / item.name, dirs_exist_ok=True)
    
    print("✅ 文件复制完成")

def main():
    """主函数"""
    print("🚀 磁盘监控系统前端构建脚本")
    print("=" * 50)
    print("项目根目录:", PROJECT_ROOT)
    print("前端目录:", FRONTEND_DIR)
    print("后端静态文件目录:", BACKEND_DIST_DIR)
    print("=" * 50)
    
    try:
        # 步骤1: 类型检查
        check_frontend_types()
        
        # 步骤2: 前端构建
        frontend_dist = build_frontend()
        
        # 步骤3: 复制前端文件到后端
        copy_frontend_to_backend(frontend_dist)
        
        print("\n" + "=" * 50)
        print("🎉 前端构建完成！")
        print("=" * 50)
        print("前端文件已复制到后端目录，可以执行后端构建了")
        print("后端静态文件路径:", BACKEND_DIST_DIR)
        
    except KeyboardInterrupt:
        print("\n用户中断构建")
        sys.exit(1)
    except Exception as e:
        print(f"构建失败: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()